package com.buss.base.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.buss.base.dao.DicDataDao;
import com.buss.base.model.DicData;
import com.buss.base.service.DicDataService;
import com.buss.core.exception.ServiceException;
import com.buss.core.persistence.OrderBy;
import com.buss.core.persistence.Paginalbe;
import com.buss.core.persistence.ResultList;
import com.buss.core.utils.StringUtil;

@Service
public class DicDataServiceImpl implements DicDataService {

	@Autowired
	private DicDataDao dicDataDao;
	
	@Override
	public DicData saveDicData(DicData dicData)  throws ServiceException{
		DicData tmpDic = loadDicData(dicData.getCompanyId(), dicData.getCode());
		if(tmpDic != null){
			throw new ServiceException("改数据字典编码已经存在，请核实!");
		}
		return dicDataDao.saveDicData(dicData);
	}

	@Override
	public void editDicData(DicData dicData) {
		dicDataDao.editDicData(dicData);
	}

	@Override
	public void removeDicData(Long[] ids)  throws ServiceException{
		String mess = "";
		for(Long id : ids){
			DicData dicData = loadDicData(id);
			if(dicData != null){
				Long cnt = dicDataDao.getRowCount(dicData.getCompanyId(), dicData.getId());
				if(cnt > 0){
					mess += "编码(Key):" + dicData.getCode() + "  名称(Value):" + dicData.getName() + "有下级数据字典</br>"; 
				}
			}
		}
		if(StringUtil.isNotEmpty(mess)){
			mess += "请先删除下级字典信息!";
			throw new ServiceException(mess);
		}
		
		dicDataDao.removeDicData(ids);
	}

	@Override
	public DicData loadDicData(Long id) {		
		return dicDataDao.loadDicData(id);
	}

	@Override
	public DicData loadDicData(String companyId, String code) {
		return dicDataDao.loadDicData(companyId, code);
	}

	@Override
	public ResultList<DicData> queryDicData(String companyId, Long parentId,String name,
			Paginalbe page,OrderBy orderBy) {
		return dicDataDao.queryDicData(companyId, parentId, name,page,orderBy);
	}

	@Override
	public ResultList<DicData> queryDicData(String companyId, String code,
			Paginalbe page,OrderBy orderBy) {
		DicData dicData = loadDicData(companyId, code);
		return queryDicData(companyId, dicData.getId(),null, page,orderBy);
	}

}
